package com.qiyuesuo.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.qiyuesuo.CommFiled;
import com.qiyuesuo.untils.DateTimeUntils;

/**
 * ew FileOutputStream(directory+getDateTime(new Date())+System.currentTimeMillis()+".pdf")
 * 生成pdf的工具类
 */
public class CreatPdfFileUntils {

    public static void createPdf() throws Exception {
        Document document = new Document(PageSize.A4.rotate());
        document.setMargins(100F, 100F, 100F, 0);
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(mkdir()+System.currentTimeMillis() + ".pdf"));
        document.addTitle("契约锁服务协议");
        //开启文档
        document.open();
        // 设置字体格式
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        //设置字体的大小和加粗
        Font font1 = new Font(base, 24, Font.BOLD);
        //写段落
        Paragraph p1 = new Paragraph();
        //设置居中 字体以及文档内容
        p1.setAlignment(Paragraph.ALIGN_CENTER);
        p1.setPaddingTop(1000F);
        p1.setFont(font1);
        p1.add("服务协议");
        document.add(p1);
        Font fontChinese = new Font(base, 18, Font.NORMAL);
        // 创建Chunk对象，设置下划线的厚度为1
        Chunk chunk1 = new Chunk("     本人", fontChinese);
        document.add(chunk1);
        // 创建Chunk对象，设置下划线的厚度为0.1
        Chunk underline = new Chunk("XXX");
        underline.setUnderline(0.01f, -2f);
        document.add(underline);
        chunk1 = new Chunk(", 身份证号：", fontChinese);
        document.add(chunk1);
        // 创建Chunk对象，设置下划线的厚度为0.1
        Chunk underline2 = new Chunk("XXXXXXXX");
        underline2.setUnderline(0.01f, -2f);
        document.add(underline2);
        chunk1 = new Chunk(CommFiled.TEMPLATE, fontChinese);
        document.add(chunk1);
        Paragraph p = new Paragraph();
        p.setFont(fontChinese);
        p.add("申请人签字：XXXX");
        p.setIndentationLeft(400);
        p.setSpacingAfter(8);
        Paragraph p2 = new Paragraph();
        p2.setFont(fontChinese);
        p2.add("日期：");
        p2.setIndentationLeft(400);
        p2.setSpacingAfter(8);
        document.add(p);
        document.add(p2);
        // 5.关闭文档
        document.close();

    }

    private static String mkdir() {

        String dateStr = DateTimeUntils.getDateTime(new Date());
        String directory = CommFiled.DOWNLOAD_DIRECTORY + dateStr;
        File file = new File(directory);
        if (!file.exists()) {
            file.mkdir();
        }
        return file.getAbsolutePath()+"\\";

    }
}
